package com.qh.servlet;

import com.qh.dao.Jdbc;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * com.qh.servlet
 * 26832
 * yjj
 * &#064;description: 保存数据
 * &#064;author: lxm
 * SaveData
 * &#064;create: 2024-06-08 06:28
 **/
@WebServlet("/save")
public class SaveData extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String dname = req.getParameter("selectedDoctor");
        System.out.println(dname);
        HttpSession session = req.getSession();
        String idcard = (String) session.getAttribute("idcard");
        //根据传递的医生id查询医生姓名
        Jdbc jdbc = new Jdbc();
        String sql ="select * from doctor where id='"+dname+"'";
        Connection con = null;
        Statement smt = null;
        ResultSet rs = null;
        String name=null;
        try{
            con = jdbc.getConnection();
            smt = con.createStatement();
            rs = smt.executeQuery(sql);
            while(rs.next()){
                name = rs.getString("uname");
            }
            //更新result表
            String sql2 = "SET @max_id := (SELECT MAX(id) FROM resoult WHERE idcard = '"+idcard+"');";
            smt.executeUpdate(sql2);
            String sql3 = "UPDATE resoult SET doctor='"+name+"' WHERE idcard='"+idcard+"' AND id = @max_id";
            int i = smt.executeUpdate(sql3);
            if(i==1){
                req.getRequestDispatcher("result.html").forward(req,resp);
            }else{
                req.getRequestDispatcher("doctor.html").forward(req,resp);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                jdbc.close(con,smt,rs);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

    }
}
